package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.lettuce.core.RedisClient;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class ManageServiceImpl implements ManageService {
    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;
    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;
    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;
    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;
    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;
    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;
    @Autowired
    private SpuInfoMapper spuInfoMapper;
    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RabbitService rabbitService;

    //获取一级分类的集合
    @Override
    public List<BaseCategory1> getCategory1() {
        List<BaseCategory1> list = baseCategory1Mapper.selectList(null);
        return list;
    }

    //获取 二级分类的集合/
    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        QueryWrapper<BaseCategory2> wrapper = new QueryWrapper<BaseCategory2>().eq("category1_id",category1Id);
        List<BaseCategory2> list = baseCategory2Mapper.selectList(wrapper);
        return list;
    }

    //获取 三级分类的集合/
    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        QueryWrapper<BaseCategory3> wrapper = new QueryWrapper<BaseCategory3>().eq("category2_id",category2Id);
        List<BaseCategory3> list = baseCategory3Mapper.selectList(wrapper);
        return list;
    }

    //根据分类id获取平台属性
    @Override
    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        List<BaseAttrInfo> list = baseAttrInfoMapper.attrInfoList(category1Id, category2Id, category3Id);
        return list;
    }

    //添加平台属性
    @Override
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //1.添加平台属性表
        baseAttrInfoMapper.insert(baseAttrInfo);
        //2.添加平台属性值
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        if (!CollectionUtils.isEmpty(attrValueList)){
            attrValueList.stream().forEach(item -> {
                //外键
                item.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(item);
            });
        }
    }

    //根据平台属性ID获取平台属性
    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        QueryWrapper<BaseAttrValue> wrapper = new QueryWrapper<BaseAttrValue>().eq("attr_id", attrId);
        List<BaseAttrValue> list = baseAttrValueMapper.selectList(wrapper);
        return list;
    }

    //修改平台属性
    @Override
    public void updateAttrInfo(BaseAttrInfo baseAttrInfo) {
        Long id = baseAttrInfo.getId();
        baseAttrInfoMapper.deleteById(id);
        List<BaseAttrValue> list = baseAttrInfo.getAttrValueList();
        if (!CollectionUtils.isEmpty(list)){
            list.stream().forEach(item -> {
                Long vId = item.getId();
                baseAttrValueMapper.deleteById(vId);
            });
        }

        this.saveAttrInfo(baseAttrInfo);
    }

    //查询品牌的分页
    @Override
    public IPage baseTrademark(Integer page, Integer limit) {
        Page<BaseTrademark> myPage = new Page<BaseTrademark>(page,limit);
        IPage<BaseTrademark> thisPage = baseTrademarkMapper.selectPage(myPage, null);
        return thisPage;
    }

    //查询商品分页(spu) 根据三级分类id
    @Override
    public IPage spuPage(Integer page, Long limit, Long category3Id) {
        IPage<SpuInfo> spuInfoPage = new Page<>(page, limit);
        QueryWrapper<SpuInfo> wrapper = new QueryWrapper<SpuInfo>()
                .eq("category3_id",category3Id);
        IPage<SpuInfo> result = spuInfoMapper.selectPage(spuInfoPage, wrapper);
        return result;
    }

    //查看品牌列表
    @Override
    public List<BaseTrademark> getTrademarkList() {
        List<BaseTrademark> list = baseTrademarkMapper.selectList(null);
        return list;
    }

    //查询所有销售属性
    @Override
    public List<BaseSaleAttr> baseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }

    //保存spu
    @Override
    public void saveSpuInfo(SpuInfo spuInfo) {
        //1.添加spu_info
        spuInfoMapper.insert(spuInfo);
        //2.添加spuImage
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        spuImageList.forEach(spuImage -> {
            spuImage.setSpuId(spuInfo.getId());
            spuImageMapper.insert(spuImage);
        });
        //3.添加spu_sale_attr
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        spuSaleAttrList.forEach(spuSaleAttr -> {
            spuSaleAttr.setSpuId(spuInfo.getId());
            spuSaleAttrMapper.insert(spuSaleAttr);

            //4.添加spu_sale_attr_value
            List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
            spuSaleAttrValueList.forEach(spuSaleAttrValue -> {
                spuSaleAttrValue.setSpuId(spuInfo.getId());
                spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                spuSaleAttrValueMapper.insert(spuSaleAttrValue);
            });
        });
    }

    //为了添加SKU 查询spuId对应的所有图片
    @Override
    public List<SpuImage> spuImageList(Long spuId) {
        return spuImageMapper.selectList(new QueryWrapper<SpuImage>()
        .eq("spu_id",spuId));
    }

    //为了添加SKU  查询spuId 对应的销售属性及属性值集合
    @Override
    public List<SpuSaleAttr> spuSaleAttrList(Long spuId) {
        return spuSaleAttrMapper.spuSaleAttrList(spuId);
    }

    //查询sku分页
    @Override
    public IPage skuPage(Integer page, Integer limit) {
        return skuInfoMapper.selectPage(new Page<SkuInfo>(page,limit),null);
    }

    //保存SKU
    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {
        //1.sku_info
        skuInfoMapper.insert(skuInfo);
        //2.skuImage
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        skuImageList.forEach(skuImage -> {
            skuImage.setSkuId(skuInfo.getId());
            skuImageMapper.insert(skuImage);
        });
        //3:sku_attr_value
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        skuAttrValueList.forEach(skuAttrValue -> {
            skuAttrValue.setSkuId(skuInfo.getId());
            skuAttrValueMapper.insert(skuAttrValue);
        });
        //4:sku_sale_attr_value
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        skuSaleAttrValueList.forEach(skuSaleAttrValue -> {
            skuSaleAttrValue.setSkuId(skuInfo.getId());
            //spu_id
            skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
            skuSaleAttrValueMapper.insert(skuSaleAttrValue);
        });

    }

    //上架
    @Override
    public void onSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.ONSALE);
        skuInfoMapper.updateById(skuInfo);
        // 发消息 给MQ索引库
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_UPPER,skuId);
    }


    //下架
    @Override
    public void canceSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.NOSALE);
        skuInfoMapper.updateById(skuInfo);
        // 发消息 给MQ索引库
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_LOWER,skuId);
    }


    private final Lock lock = new ReentrantLock();

    //1.根据skuId 查询库存表  通过主键   同时获取此库存的图片集合
    @Override //分布式锁解决缓存击穿问题 使用Redisson
    public SkuInfo getSkuInfo(Long skuId) {
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;//RedisKey的规范
        String cacheKeyLock = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;//RedisKey的规范
        //先查询缓存
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        if (null == skuInfo){ //如果没有值
            RLock lock = redissonClient.getLock(cacheKeyLock);//cacheKeyLock : 锁的名称
            //参数1: 尝试多久获取锁
            //参数2: 获取锁的持有时间
            try {
                boolean isLock =
                        lock.tryLock(RedisConst.SKULOCK_EXPIRE_PX1, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                if (isLock == true){
                    //查询db
                    try {
                        //上锁了
                        skuInfo = skuInfoMapper.selectById(skuId);
                        //查询对应skuId的图片并添加到skuInfo中
                        if (null != skuInfo){
                            List<SkuImage> list = skuImageMapper.selectList(new QueryWrapper<SkuImage>()
                                    .eq("sku_id", skuId));
                            skuInfo.setSkuImageList(list);
                            //保存缓存一份
                            redisTemplate.opsForValue().set(cacheKey,skuInfo,
                                    RedisConst.SKUKEY_TIMEOUT+new Random().nextInt(300),
                                    TimeUnit.SECONDS);//缓存雪崩
                        }else{
                            //缓存穿透
                            skuInfo = new SkuInfo();
                            redisTemplate.opsForValue().set(cacheKey,skuInfo,5,TimeUnit.MINUTES);
                        }
                    } finally {
                        lock.unlock();//解锁
                    }
                } else {
                    //没有上锁
                    TimeUnit.SECONDS.sleep(2);
                    skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return skuInfo;
    }

    //@Override  本地锁方式解决缓存击穿问题
    public SkuInfo getSkuInfo1(Long skuId) {
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;//RedisKey的规范
        //先查询缓存
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        if (null == skuInfo){
            //缓存击穿  必须上过期不候锁,不能上不见不散锁
            try {
                boolean tryLock = lock.tryLock(1, TimeUnit.SECONDS);
                if (tryLock == true){
                    try {
                        //上锁了
                        skuInfo = skuInfoMapper.selectById(skuId);
                        //查询对应skuId的图片并添加到skuInfo中
                        if (null != skuInfo){
                            List<SkuImage> list = skuImageMapper.selectList(new QueryWrapper<SkuImage>()
                                    .eq("sku_id", skuId));
                            skuInfo.setSkuImageList(list);
                            //保存缓存一份
                            redisTemplate.opsForValue().set(cacheKey,skuInfo,
                                    RedisConst.SKUKEY_TIMEOUT+new Random().nextInt(300),
                                    TimeUnit.SECONDS);//缓存雪崩
                        }else{
                            //缓存穿透
                            skuInfo = new SkuInfo();
                            redisTemplate.opsForValue().set(cacheKey,skuInfo,5,TimeUnit.MINUTES);
                        }
                    } finally {
                        lock.unlock();//解锁
                    }
                }else {
                    //没有上锁
                    TimeUnit.SECONDS.sleep(2);
                    skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


        }
        return skuInfo;
    }

    //2.获取123级分类 根据category3Id
    @Override
    @GmallCache(prefix = "getBaseCategoryView")
    public BaseCategoryView getBaseCategoryView(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }

    //3. 单独查询价格 实时价格
    @Override
    //@GmallCache(prefix = "getPrice")
    public BigDecimal getPrice(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        BigDecimal price = skuInfo.getPrice();
        if (null != price){
            return price;
        }
        return null;
    }

    //4.查询销售属性及其选中
    @Override
    @GmallCache(prefix = "getSpuSaleAttrListCheckBySku")
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long spuId, Long skuId) {
        return spuSaleAttrMapper.getSpuSaleAttrListCheckBySku(spuId,skuId);
    }

    //5.查询组合对应的SKUID 为了销售属性的选择 跳转 刷新功能
    @Override
    @GmallCache(prefix = "getSkuValueIdsMap")
    public Map getSkuValueIdsMap(Long spuId) {
        List<Map> list = skuSaleAttrValueMapper.getSkuValueIdsMap(spuId);
        Map map = new HashMap();
        list.forEach(item ->{
            map.put(item.get("value_ids"),item.get("sku_id"));
        });
        return map;
    }

    //6：查询所有分类视图 集合
    @Override
    public List<BaseCategoryView> getBaseCategoryViewList() {
        return baseCategoryViewMapper.selectList(null);
    }

    @Override
    public BaseTrademark getBaseTrademark(Long tmId) {
        BaseTrademark baseTrademark = baseTrademarkMapper.selectById(tmId);
        return baseTrademark;
    }

    //8.查询某一款商品的平台属性集合
    @Override
    public List<SkuAttrValue> getSkuAttrValueAndAttrAndAttrValue(Long skuId) {
        List<SkuAttrValue> list = skuAttrValueMapper.getSkuAttrValueAndAttrAndAttrValue(skuId);
        return list;
    }



    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SpuImageMapper spuImageMapper;
    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;
    @Autowired
    private SkuInfoMapper skuInfoMapper;
    @Autowired
    private SkuImageMapper skuImageMapper;
    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;
    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;
    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;
}
